﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace SuperMicroWave.Common
{
    public class HashTableHelper
    {
        private Hashtable aa;
        private string path;

        public HashTableHelper(string p)
        {
            aa = new Hashtable();
            path = p;
        }

        public bool HasValue()
        {
            return aa.Count > 0;
        }

        public void ClearValue()
        {
            if (File.Exists(path))
                File.Delete(path);
            aa.Clear();
        }

        public double GetValue(double key)
        {
            if (aa.Count == 0)
                return key;
            else
            {
                double temp = Math.Round(key, 1);
                double dLow = temp;
                double dUp = temp;
                int nCount = 10;
                while (true)
                {
                    if (nCount == 0)
                        return key;
                    if (aa.ContainsKey(dLow) && aa.ContainsKey(dUp))
                    {
                        return ((double)aa[dLow]! + (double)aa[dUp]!) / 2;
                    }
                    if (!aa.ContainsKey(dLow))
                        dLow -= 0.1;
                    if (!aa.ContainsKey(dUp))
                        dUp += 0.1;

                    nCount--;
                }
            }
        }

        public void SaveHashTable(List<double> key, List<double> value)
        {
            aa.Clear();

            int num = key.Count > value.Count ? value.Count : key.Count;

            for (int i = 0; i < num; i++)
            {
                double dkey = Math.Round(key[i], 1);
                double dvalue = value[i];
                if (!aa.ContainsKey(dkey))
                    aa.Add(dkey, dvalue);
            }

            FileStream fs = new FileStream(path, FileMode.Create);
            JsonSerializer.Serialize(fs, aa);
            fs.Close();
        }

        public void LoadHashTable()
        {
            aa.Clear();

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            try
            {
                aa = JsonSerializer.Deserialize<Hashtable>(fs)!;
            }
            catch (Exception ex) { }
            fs.Close();
        }
    }
}
